package cn.bupt.adt.controller;

import cn.bupt.adt.constant.Constants;
import cn.bupt.adt.entity.autogenerate.*;
import cn.bupt.adt.model.FinanceModel;
import cn.bupt.adt.model.WithdrawModel;
import cn.bupt.adt.service.IDoctorAppUserService;
import cn.bupt.adt.service.IFinanceService;
import cn.bupt.adt.service.IInstitutionAppUserService;
import cn.bupt.adt.service.IWithdrawService;
import cn.bupt.adt.util.NetDataAccessUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/financeManagement")
public class FinanceController {

    @Autowired
    IFinanceService financeService;

    @Autowired
    IWithdrawService withdrawService;

    @Autowired
    IDoctorAppUserService doctorAppUserService;

    @Autowired
    IInstitutionAppUserService institutionAppUserService;

    @RequestMapping("/index/{pageNum}")
    public ModelAndView index(@PathVariable("pageNum") int pageNum, @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                              @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime, String name) {
        ModelAndView mv = new ModelAndView(Constants.FINANCE_INDEX);
//		System.out.println("startTime:"+startTime.toLocaleString());
//		System.out.println("endTime:"+endTime.toLocaleString());
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE);
        List<FinanceModel> finances = null;
        if (name == null || "".equals(name))
            finances = financeService.getFinanceByDate(startTime, endTime);
        else
            finances = financeService.getFinanceByDateAndName(startTime, endTime, name);
        System.out.println(name);
        mv.addObject("allPages", page.getPages());
        mv.addObject("currentPage", page.getPageNum());
        mv.addObject("finances", finances);
        mv.addObject("startTime", startTime);
        mv.addObject("endTime", endTime);
        mv.addObject("name", name);
        return mv;
    }

    @RequestMapping("/withdraw/{pageNum}")
    public ModelAndView withdraw(@PathVariable("pageNum") int pageNum) {
        ModelAndView mv = new ModelAndView(Constants.WITHDRAW_INDEX);
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE, "");
        List<WithdrawModel> withdrawModels = withdrawService.getAllWithdraws();
        mv.addObject("withdrawModels", withdrawModels);
        mv.addObject("allPages", page.getPages());
        mv.addObject("currentPage", page.getPageNum());
        return mv;
    }

    @RequestMapping("/undealedwithdraw/{pageNum}")
    public ModelAndView unDealedwithdraw(@PathVariable("pageNum") int pageNum) {
        ModelAndView mv = new ModelAndView(Constants.WITHDRAW_UNDEALED);
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE, "");
        List<WithdrawModel> withdrawModels = withdrawService.getUndealedWithdraws();
        mv.addObject("withdrawModels", withdrawModels);
        mv.addObject("allPages", page.getPages());
        mv.addObject("currentPage", page.getPageNum());
        return mv;
    }

    @RequestMapping("/updateWithdrawStatus")
    @ResponseBody
    public Object updateWithdrawStatus(@RequestBody Withdraw w) {
        NetDataAccessUtil nau = new NetDataAccessUtil();
        Withdraw withdraw = withdrawService.getWithdrawById(w.getId());
        Finance finance = new Finance();
        finance.setTime(new Date());
        finance.setMoney(withdraw.getMoney());
        finance.setFlag(Constants.OUTCOME);
        if (withdrawService.updateWithdrawStatus(w)) {
            if (withdraw.getFlag().equals(Constants.DOC_WITHDRAW)) {
                DoctorAppUser doc = doctorAppUserService.getDoctorById(withdraw.getUserId());
                doc.setWaitedToBeWithdrawnMoney(doc.getWaitedToBeWithdrawnMoney() - withdraw.getMoney());
                finance.setName(doc.getName());
                doctorAppUserService.updateDoctorAppuser(doc);
            } else {
                InstitutionView ins = institutionAppUserService.getInstitutionViewById(withdraw.getUserId());
                ins.setWaitedToBeWithdrawnMoney(ins.getWaitedToBeWithdrawnMoney() - withdraw.getMoney());
                finance.setName(ins.getName());
                InstitutionAppUser institutionAppUser = new InstitutionAppUser();
                institutionAppUser.setWaitedToBeWithdrawnMoney(ins.getWaitedToBeWithdrawnMoney());
                institutionAppUser.setId(ins.getId());
                institutionAppUserService.updateInstitutionAppUser(institutionAppUser);
            }
            financeService.addFinance(finance);
            nau.setResultDesp("成功处理提现请求");
            nau.setResult(1);
        } else {
            nau.setResultDesp("因网络或其他原因处理失败，请稍后再试");
            nau.setResult(0);
        }
        return nau;
    }

    @RequestMapping(value = "/exportExcel")
    public void ExportExcelUserStatistics(String name,
                                          @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                          @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
                                          HttpServletResponse response) {
        financeService.exportFinanceExcel(startTime, endTime, response, name);
    }
}
